package com.coscon.controller;

import com.coscon.controller.base.BaseController;
import com.coscon.model.IrcaFile;
import com.coscon.model.ResponseResult;
import com.coscon.model.api.ResponseCode;
import com.coscon.service.ConfigService;
import com.coscon.service.FileService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;


/**
 * 文件浏览
 */
@Slf4j
@Controller
@RequestMapping("/jm/manager/fileBrower")
public class FileBrowerController extends BaseController {

    @Resource
    private FileService fileService;
    @Resource
    private ConfigService configService;


    @GetMapping("/index")
    public ModelAndView welcomePage(HttpServletRequest request
            , @RequestParam(value = "path", required = false) String path
    ){
        if(StringUtils.isBlank(path)){
            //先获取最近一次访问的路径
            path = this.fileService.getLastFilePathLog();
               if(StringUtils.isBlank(path)){
                   path = this.fileService.getUserHomePath();//如果path参数为空，默认为用户主目录
               }
        }else{
            path = this.fileService.filePathDecrypt(path);
        }
        log.debug("path:" +path );
        ModelAndView v = new ModelAndView("appPage/fileBrowerOper");
        List<IrcaFile> fileList = this.fileService.getFileList(path);
        v.addObject("fileList",fileList);
        //配置中，是否允许删除文件
        String fileIsDeleteFile = this.configService.getSysconfigValByKey("file_is_delete_file");
        boolean isAlowDeleteFile = StringUtils.equalsIgnoreCase(fileIsDeleteFile,"on");
        v.addObject("isAlowDeleteFile",isAlowDeleteFile);

        return v;
    }

    /**
     * 打开文件
     * @param filePath
     * @return
     */
    @PostMapping("/openFile")
    public @ResponseBody
    ResponseResult<Boolean> openFile(
            @RequestParam(value="filePath",required=true) String filePath
    ){
       String path = this.fileService.filePathDecrypt(filePath);
       log.debug("打开文件的路径：" + path);
       boolean f = this.fileService.openFile(path);
        return new ResponseResult(ResponseCode.OK.getCode(),ResponseCode.OK.getMsg(),f);
    }

    /**
     * 删除文件
     * @param filePath
     * @return
     */
    @PostMapping("/deleteFile")
    public @ResponseBody
    ResponseResult<Boolean> deleteFile(
            @RequestParam(value="filePath",required=true) String filePath //
    ){
        String path = this.fileService.filePathDecrypt(filePath);
        log.debug("删除文件的路径：" + path);
        boolean f = this.fileService.deleteFile(path);
        return new ResponseResult(ResponseCode.OK.getCode(),ResponseCode.OK.getMsg(),f);
    }




}
